import requests
from lxml import etree

# 方案一、在浏览器登录以后手动复制
cookies = {
	"sessionid": "eu225yyzcnolkwabngb36lv0zv1lrz2e"
}
res = requests.get("http://127.0.0.1:8000/admin/", cookies=cookies)

tree = etree.HTML(res.text)
title = tree.xpath("//title/text()")[0]
print(title)


# 方案二
# 使用session
session = requests.Session()
# 空
print(session.cookies)
res = session.get("http://127.0.0.1:8000/admin/login/?next=/admin/")
# csrftoken
print(session.cookies)
tree = etree.HTML(res.text)
csrfmiddlewaretoken = tree.xpath('//input[@name="csrfmiddlewaretoken"]/@value')[0]

res = session.post("http://127.0.0.1:8000/admin/login/?next=/admin/", data={
	"csrfmiddlewaretoken": csrfmiddlewaretoken,
	"username": "admin",
	"password": "123456",
	"next": "/admin/"
})
# csrftoken  sessionid
print(session.cookies)

tree = etree.HTML(res.text)
title = tree.xpath("//title/text()")[0]
print(title)



# 方案三

res = requests.get("http://127.0.0.1:8000/admin/login/?next=/admin/")
tree = etree.HTML(res.text)
csrfmiddlewaretoken = tree.xpath('//input[@name="csrfmiddlewaretoken"]/@value')[0]
res = requests.post("http://127.0.0.1:8000/admin/login/?next=/admin/", data={
	"csrfmiddlewaretoken": csrfmiddlewaretoken,
	"username": "admin",
	"password": "123456",
	"next": "/admin/"
}, cookies=res.cookies)
tree = etree.HTML(res.text)
title = tree.xpath("//title/text()")[0]
print(title)


